from django.shortcuts import render
from QQLoginTool.QQtool import OAuthQQ
from django.conf import settings
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.generics import GenericAPIView

from carts.utils import merge_cookie_redis_cart
from oauth.utils import generate_sign_openid
from .models import OAuthQQUser, OAuthSinaUser
from . import serializers

class OAuthQQLoginView(APIView):
    def get(self,request):
        #1,获取参数
        state = request.query_params.get("state","/")

        #2,创建qq对象
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                client_secret=settings.QQ_CLIENT_SECRET,
                redirect_uri=settings.QQ_REDIRECT_URI,
                state=state)

        #3,返回qq登陆页面
        login_url = oauth_qq.get_qq_url()
        return Response({"auth_url":login_url})

class OAuthQQUserView(GenericAPIView):
    serializer_class = serializers.OAuthQQUserSerializer

    def get(self,request):
        #1,获取参数code,校验
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        #2,根据code获取access_token
        oauth_qq = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                           client_secret=settings.QQ_CLIENT_SECRET,
                           redirect_uri=settings.QQ_REDIRECT_URI,
                           state="/")
        access_token = oauth_qq.get_access_token(code)


        #3,根据access_token获取openid
        openid = oauth_qq.get_open_id(access_token)

        #4,通过openid查询qq对象用户
        try:
            oauth_qq_user = OAuthQQUser.objects.get(openid=openid)
        except OAuthQQUser.DoesNotExist:
            #4,1初次授权
            sign_openid = generate_sign_openid(openid)
            return Response({"access_token":sign_openid})
        else:
            #5,非初次授权
            user = oauth_qq_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            #合并购物车,返回
            response = Response({
                "token":token,
                "username":user.username,
                "user_id":user.id
            })

            response = merge_cookie_redis_cart(request, user, response)

            return response

    def post(self,request):
        #1,获取参数
        dict_data = request.data

        #2,创建序列化器
        serializer = self.get_serializer(data=dict_data)

        #3,校验,入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        #3,1根据用户数据,生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并购物车,返回
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })

        response = merge_cookie_redis_cart(request, user, response)

        return response



# # 生成请求的url
# request_url = 'https://api.weibo.com/oauth2/authorize?client_id={client_id}&redirect_uri={redirect_uri}'.format(client_id=settings.APP_KEY,redirect_uri=settings.REDIRECT_URI)

app_key = settings.APP_KEY
app_secret = settings.APP_SECRET
redirect_uri = settings.REDIRECT_URI

from .sinaweibopy3 import APIClient

class OAuthSinaLoginView(APIView):
    def get(self,request):
        # client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=redirect_uri)

        # 生成微博返回url
        # login_url = client.get_authorize_url()
        login_url = 'https://api.weibo.com/oauth2/authorize?client_id={0}&redirect_uri={1}'.format(settings.APP_KEY,settings.REDIRECT_URI)

        # 返回url
        return Response({'auth_url':login_url})


#
class OAuthSinaUserView(GenericAPIView):
    serializer_class = serializers.OAuthSinaUserSerializer

    def get(self,request):
        # 1.获取参数
        code = request.query_params.get("code")
        if not code:
            return Response("code丢失了")

        # 2.创建代理对象
        client = APIClient(app_key=app_key, app_secret=app_secret, redirect_uri=redirect_uri)

        # 3.根据code得到assess_token
        access_token = client.request_access_token(code=code).get('access_token')

        # 4,通过access_token查询sina对象用户
        try:
            oauth_sina_user = OAuthSinaUser.objects.get(access_token=access_token)
        except OAuthSinaUser.DoesNotExist:
            # 4,1初次授权
            sign_access_token = generate_sign_openid(access_token)
            return Response({"access_token":sign_access_token})
        else:
            # 5,非初次授权
            user = oauth_sina_user.user

            from rest_framework_jwt.settings import api_settings
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)

            # 合并购物车,返回
            response = Response({
                "token":token,
                "username":user.username,
                "user_id":user.id
            })

            response = merge_cookie_redis_cart(request, user, response)

            return response

    def post(self, request):
        # 1,获取参数
        dict_data = request.data

        # 2,创建序列化器
        serializer = self.get_serializer(data=dict_data)

        # 3,校验,入库
        serializer.is_valid(raise_exception=True)
        user = serializer.save()

        # 3,1根据用户数据,生成token
        from rest_framework_jwt.settings import api_settings
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)

        # 合并购物车,返回
        response = Response({
            "token": token,
            "username": user.username,
            "user_id": user.id
        })

        response = merge_cookie_redis_cart(request, user, response)

        return response



